<?php

namespace App\Http\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class Rank extends Model
{
    /**
     * 设置排行
     *
     * @param [type] $uid
     * @param [type] $score
     * @return void
     */
    public static function set($uid, $score) {
        self::reset();
        Redis::ZINCRBY('ActiveRank', $score, $uid);
    }

    /**
     * 获取排行列表
     *
     * @param [type] $start
     * @param [type] $end
     * @return []
     */
    public static function gets($start, $end, $is_lw = false) {
        $key = 'ActiveRank';
        if($is_lw) $key = 'ActiveRankLW';
        self::reset();
        return Redis::ZREVRANGE($key, $start, $end, ['withscores'=>true]);
    }

    /**
     * 获取某一个用户的排名和分数
     *
     * @param [type] $uid
     * @return void
     */
    public static function getOne($uid, $is_lw = false) {
        $key = 'ActiveRank';
        if($is_lw) $key = 'ActiveRankLW';
        self::reset();
        $index = Redis::ZREVRANK($key, $uid);
        if(is_numeric($index)) $index++;
        else $index = 0;

        $score = intval(Redis::ZSCORE($key, $uid));

        return [ 'index' => $index, 'score' => $score ];
    }

    /**
     * 重置
     *
     * @return void
     */
    public static function reset() {
        // 每周一零点重置
        $now = time();
        $need_refre_active_time = Redis::GET('ActiveRankRefreTime') ?? 0;
        if( $now >= $need_refre_active_time ) {
            $now_week = date('N', $now);
            $now_day = strtotime(date('Y-m-d 00:00:00', $now));
            $next_refre_time = $now_day + ( ( 7 - ( $now_week - 1 ) ) * 86400 );
            Redis::SET( 'ActiveRankRefreTime', $next_refre_time );
            // 更新榜单, 本周变上周
            Redis::DEL('ActiveRankLW');
            Redis::RENAME('ActiveRank', 'ActiveRankLW');

            $config = DB::table('active_rank')->where('id', 3)->first();
            if(!empty($config) && !empty($config['val'])) {
                DB::table('active_rank')->where('id', 3)->update([
                    'val'=> ( $config['val'] + 1 ),
                    'time' => $now,
                ]);
            } else {
                DB::statement("REPLACE INTO active_rank(id, name, val, `time`) values (3, '排行榜期数', 1, $now )");
            }
        }
    }
}
